{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import timeit"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [],
   "source": [
    "#https://zhuanlan.zhihu.com/p/40695917#"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 32,
   "metadata": {},
   "outputs": [],
   "source": [
    "def mergeSort(alist):\n",
    "    n = len(alist)\n",
    "    __mergeSort(alist, 0, n-1)\n",
    "def __mergeSort(alist, start, end):\n",
    "    if (end-start <= 15):\n",
    "        insertionSortHelp(alist, start, end)\n",
    "        return\n",
    "    if start >= end:\n",
    "        return\n",
    "    mid = (start + end) // 2\n",
    "    __mergeSort(alist, start, mid)\n",
    "    __mergeSort(alist, mid + 1, end)\n",
    "    if alist[mid] > alist[mid+1]:\n",
    "        merge(alist, start, mid, end)\n",
    "def merge(alist, start, mid, end):\n",
    "    blist = alist[start:end+1]\n",
    "    l = start\n",
    "    k = mid + 1\n",
    "    pos = start\n",
    "    while pos <= end:\n",
    "        if (l > mid):\n",
    "            alist[pos] = blist[k-start]\n",
    "            k += 1\n",
    "        elif (k > end):\n",
    "            alist[pos] = blist[l-start]\n",
    "            l += 1\n",
    "        elif blist[l-start] <= blist[k-start]:\n",
    "            alist[pos] = blist[l-start]\n",
    "            l += 1\n",
    "        else:\n",
    "            alist[pos] = blist[k-start]\n",
    "            k += 1\n",
    "        pos += 1\n",
    "def insertionSortHelp(alist,l, r):\n",
    "    for i in range(l+1,r+1):\n",
    "        currentvalue=alist[i]\n",
    "        position=i\n",
    "        while alist[position-1]>currentvalue and position>l:\n",
    "            alist[position]=alist[position-1]\n",
    "            position=position-1\n",
    "        alist[position]=currentvalue\n",
    "    return alist"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 33,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "432 ms ± 142 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)\n"
     ]
    }
   ],
   "source": [
    "%%timeit -n 10\n",
    "a=list(range(100000,0,-1))\n",
    "mergeSort(a)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.9"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
